package org.testis.testdriver.translation;

import java.util.HashMap;

/**
 *
 * @author barisergun
 */
public class AtofDutValueTranslateAction extends AtofValueTranslateAction {

    private HashMap<String, String> m_dutvaluemap;

    public AtofDutValueTranslateAction(HashMap<String, String> dutvaluemap) {
        m_dutvaluemap = dutvaluemap;
    }

    @Override
    public String operateRequest(String dataPointer) {
        if (m_dutvaluemap != null) {
            String parseVal = AtofTranslationConstants.DUT_VALUE_CONSTANT;
            String endVal = "@";
            int beginIndex = dataPointer.indexOf(parseVal);
            while (beginIndex != -1) {

                int keyBeginIndex = beginIndex + parseVal.length();

                int keyEndIndex;

                if (dataPointer.indexOf(endVal,
                        keyBeginIndex) != -1) {
                    keyEndIndex = dataPointer.indexOf(endVal,
                            keyBeginIndex) + 1;
                } else if (dataPointer.indexOf(" ",
                        keyBeginIndex) != -1) {
                    keyEndIndex = dataPointer.indexOf(" ",
                            keyBeginIndex);
                } else if (dataPointer.indexOf('\0',
                        keyBeginIndex) != -1) {
                    keyEndIndex = dataPointer.indexOf('\0',
                            keyBeginIndex);
                } else {
                    keyEndIndex = dataPointer.length();
                }

                String keyPointer = dataPointer.substring(
                        keyBeginIndex,
                        keyEndIndex);
                keyPointer = keyPointer.replace(endVal,
                        "");

                String toBeReplaced = dataPointer.substring(beginIndex,
                        keyEndIndex);

                String replacing = m_dutvaluemap.get(keyPointer);

                if (replacing == null) {
                    String exceptString = "No value found for DUT Key: " + keyPointer;
                    if (!m_exceptions.containsKey(keyPointer)) {
                        m_exceptions.put(keyPointer, exceptString);
                    }

                    replacing = keyPointer.replace(AtofTranslationConstants.
                            DUT_VALUE_CONSTANT, "").replace("#", "");

                }
                dataPointer = dataPointer.replace(toBeReplaced,
                        replacing);
                beginIndex = dataPointer.indexOf(parseVal,
                        0);


            }
        }

        return dataPointer;
    }
}
